package com.thwj.project.amap;

import com.alibaba.fastjson.JSON;
import com.thwj.common.exception.ServiceException;
import com.thwj.common.utils.http.OkHttpClientHelper;
import com.thwj.framework.config.AMapConfig;
import com.thwj.framework.redis.RedisCache;
import com.thwj.project.biz.domain.Area;
import com.thwj.project.amap.dto.AppLocationDTO;
import com.thwj.project.amap.jsonbean.AMapLocation;
import com.thwj.project.biz.service.IAreaService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Slf4j
@Service
public class AMapService {


    @Autowired
    RedisCache redisCache;
    @Autowired
    OkHttpClientHelper okHttpClientHelper;
    @Autowired
    AMapConfig aMapConfig;
    @Autowired
    IAreaService areaService;

    /***
     * 高德Key  用户在高德地图官网申请Web服务API类型Key  必填
     *
     * location  经纬度坐标  传入内容规则：经度在前，纬度在后，经纬度间以“,”分割，经纬度小数点后不要超过 6 位。
     */
    private static final String AMAP_LOCATION_URL = "https://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s";

    /***
     * redis key值 避免 用户请求付费接口次数太频繁
     */
    public static final String REDIS_LNG_LAT_LOCATION = "LNG_LAT_LOCATION";

    /***
     * 根据经纬度获取行政地址信息 英文逗号隔开
     * @param lngLat
     * @return
     */
    public AppLocationDTO getAppLocationDTO(String lngLat) {
        AppLocationDTO appLocationDTO = redisCache.getCacheMapValue(REDIS_LNG_LAT_LOCATION, lngLat);
        if(appLocationDTO == null) {
            appLocationDTO = convertAppLocationDTO(getAMapLocation(lngLat));
            redisCache.setCacheMapValue(REDIS_LNG_LAT_LOCATION, lngLat, appLocationDTO);
        }
        return appLocationDTO;
    }

    public AMapLocation getAMapLocation(String lngLat){
        final String url = String.format(AMAP_LOCATION_URL, aMapConfig.getKey(), lngLat);
        log.info("地址转换请求URL:{}", url);
        final Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = okHttpClientHelper.getClient().newCall(request).execute()) {
            log.info("数据外送完成,返回内容:{}", response);
            if (response.code() != 200) {
                throw new ServiceException("地址转换异常");
            }
            // 处理请求
            AMapLocation aMapLocation = JSON.parseObject(response.body().string(),AMapLocation.class);
            return aMapLocation;
        } catch (IOException e) {
            log.info("数据外送异常,{}", e);
            throw new ServiceException("地址转换异常");
        }
    }

    public AppLocationDTO convertAppLocationDTO(AMapLocation location) {
        String acode = location.getRegeocode().getAddressComponent().getAdcode();
        // 直接根据acode 获取 省市区信息
        Area currentArea = areaService.getById(Long.parseLong(acode));
        AppLocationDTO appLocationDTO = new AppLocationDTO();
        appLocationDTO.setNameDistrict(currentArea.getAreaName());
        appLocationDTO.setCodeDistrict(currentArea.getAreaCode());
        appLocationDTO.setCodeCity(currentArea.getCityCode());
        appLocationDTO.setNameCity(currentArea.getCityName());
        appLocationDTO.setCodeProv(currentArea.getProCode());
        appLocationDTO.setNameProv(currentArea.getProName());
        return appLocationDTO;
    }
}
